/**
 * 
 */
package org.footito.android.api;

import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 * Target : http://api.footito.fr/avatar/list
 * http://api.footito.fr/avatar/list?updated_after=###TON_TIMESTAMP####
 * 
 * @author Julien
 * 
 */
public class TeamApiHandler extends DefaultHandler {

	public final static String URL_API = "http://api.footito.fr/avatar/list";
	public final static String URL_API_UPDATED_AFTER = "updated_after";

	private String name;
	private String picture;
	private String link;
	private int id;
	private ArrayList<TeamFromAPI> mTeamList = new ArrayList<TeamFromAPI>();
	private int group;

	/**
	 * 
	 */
	public TeamApiHandler() {
	}
	
	public ArrayList<TeamFromAPI> getTeamList() {
		return mTeamList;
	}

	@Override
	public void startDocument() throws SAXException {
	}

	@Override
	public void endDocument() throws SAXException {
	}

	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		if (localName.equals(TAG.team)) {
			IN.team = true;
			id = Integer.parseInt(attributes.getValue(TAG.id));
			group = Integer.parseInt(attributes.getValue(TAG.group));
		} else if (localName.equals(TAG.name)) {
			IN.name = true;
			name = "";
		} else if (localName.equals(TAG.picture)) {
			IN.picture = true;
			picture = "";
		} else if (localName.equals(TAG.link)) {
			IN.link = true;
			link = "";
		}
	}

	@Override
	public void endElement(String uri, String localName, String qName) throws SAXException {
		if (localName.equals(TAG.team)) {
			IN.team = false;
			TeamFromAPI currentTeam = new TeamFromAPI(id, name, picture, link, group);
			if (currentTeam.isValid())
				mTeamList.add(currentTeam);
		} else if (localName.equals(TAG.name)) {
			IN.name = false;
		} else if (localName.equals(TAG.picture)) {
			IN.picture = false;
		} else if (localName.equals(TAG.link)) {
			IN.link = false;
		}
	}

	public void characters(char[] ch, int start, int length) throws SAXException {
		if (IN.name) {
			this.name += new String(ch, start, length);
		} else if (IN.link) {
			this.link += new String(ch, start, length);
		} else if (IN.picture) {
			this.picture += new String(ch, start, length);
		}
	};

	private static class IN {
		private static boolean team;
		private static boolean name;
		private static boolean picture;
		private static boolean link;
	}

	private static class TAG {
		private final static String team = "team";
		private final static String name = "name";
		private final static String picture = "picture";
		private final static String link = "link";
		private final static String id = "id";
		private final static String group = "group";
	}
}
